package com.itheima.d2_udp1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * UDP服务端：接收数据
 */
public class Server {
    public static void main(String[] args) throws IOException {
        //1.创建DatagramSocket对象，准备接收数据
        DatagramSocket socket = new DatagramSocket(10000);
        //2.创建一个数据包，用于接收数据
        byte[] bytes = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
        //3.接收数据
        socket.receive(packet);
        //解析数据
        String s = new String(packet.getData(), 0, packet.getLength());
        System.out.println(s);
        System.out.println("===========");
        int length = packet.getLength();
        String hostAddress = packet.getAddress().getHostAddress();
        String name = packet.getAddress().getHostName();
        System.out.println("数据长度："+length);
        System.out.println("数据来源："+hostAddress);
        System.out.println("数据主机名："+name);
        System.out.println("数据来源："+packet.getPort());

        //4.释放资源
        socket.close();
    }
}
